use gtk::prelude::*;
use gtk::{Button, Grid, Window, WindowType};

fn create_keyboard_window<F>(key_press_callback: F) -> Window
where
    F: 'static + Fn(u32),
{
    // 创建主窗口
    let window = Window::new(WindowType::Toplevel);
    window.set_title("Virtual Keyboard");
    window.set_default_size(400, 300);

    // 创建网格布局
    let grid = Grid::new();
    window.add(&grid);

    // 创建按键
    let keys = vec![
        ('Q', 16), ('W', 17), ('E', 18), ('R', 19), ('T', 20), 
        ('Y', 21), ('U', 22), ('I', 23), ('O', 24), ('P', 25)
    ];

    for (i, (label, key_code)) in keys.iter().enumerate() {
        let button = Button::with_label(&label.to_string());
        button.connect_clicked({
            let key_press_callback = key_press_callback.clone();
            let key_code = *key_code;
            move |_| {
                key_press_callback(key_code); // 调用回调发送按键事件
            }
        });
        grid.attach(&button, (i % 10) as i32, (i / 10) as i32, 1, 1);
    }

    window
}


use wayland_client::{Display, GlobalManager};
use wayland_protocols::unstable::input_method::v1::client::zwp_input_method_v1::ZwpInputMethodV1;

fn initialize_wayland() -> ZwpInputMethodV1 {
    // 连接到 Wayland 显示服务器
    let display = Display::connect_to_env().expect("Failed to connect to Wayland display");
    let mut event_queue = display.create_event_queue();
    let attached_display = (*display).clone().attach(event_queue.token());

    // 获取全局对象
    let global_manager = GlobalManager::new(&attached_display);
    event_queue.sync_roundtrip(&mut (), |_, _, _| {}).unwrap();

    // 初始化 Input Method 协议
    global_manager
        .instantiate_exact::<ZwpInputMethodV1>(1)
        .expect("Input Method protocol not supported")
}

fn send_key_event(input_method: &ZwpInputMethodV1, key_code: u32) {
    input_method.key(0, 0, key_code, 1); // 按下
    input_method.key(0, 0, key_code, 0); // 松开
}


use gtk::Application;

fn main() {
    // 初始化 GTK 应用
    let app = Application::new(Some("com.example.virtual_keyboard"), Default::default());

    app.connect_activate(|app| {
        // 初始化 Wayland
        let input_method = initialize_wayland();

        // 创建虚拟键盘窗口
        let window = create_keyboard_window(move |key_code| {
            send_key_event(&input_method, key_code);
        });

        // 将窗口添加到应用并显示
        window.set_application(Some(app));
        window.show_all();
    });

    app.run();
}
